import { defineStore } from 'pinia'
import axios from '../utils/myAxios'

export interface UserType {
  username: string
  isLogin: boolean
  avatar: string
  likes: number[]
}

interface State {
  user: UserType
}

export const useUserStore = defineStore('User', {
  state: (): State => {
    return {
      user: {
        username: '',
        isLogin: false,
        avatar: 'http://localhost:3000/lujing.svg',
        likes: []
      }
    }
  },

  actions: {
    async signup(userInfo: { username: string; password: string }) {
      try {
        const response = await axios({
          method: 'post',
          url: 'http://localhost:3000/user/signup',
          data: userInfo
        })
        if (response.data.status === 1) {
          return true // 注册成功
        } else {
          return false // 注册失败
        }
      } catch (error) {
        console.log(error)
      }
    },

    async login(userInfo: { username: string; password: string }) {
      try {
        const response = await axios({
          method: 'post',
          url: 'http://localhost:3000/user/login',
          data: userInfo
        })
        if (response.status === 1) {
          this.user.isLogin = true // 登录成功后设置状态为【已登录】
          this.user.username = userInfo.username // 设置当前登录用户的用户名
          this.user.avatar = response.data.avatar // 设置当前登录用户的头像链接
          // const token = response.data.token
          // localStorage.setItem('token', token) // 登录成功后保存token
          // axios.defaults.headers.common['Authorization'] = `Bearer ${token}` // 为之后的请求都带上token
          // 登录成功之后查询该用户点赞过的所有留言
          await this.fetchUserLikes()
          return true // 登录成功
        } else {
          return false // 登录失败
        }
      } catch (error) {
        console.log(error)
      }
    },

    async fetchCurrentUser() {
      try {
        const token = localStorage.getItem('token')
        // axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        const response = await axios({
          method: 'get',
          url: 'http://localhost:3000/user/current'
        })
        if (response.status === 1) {
          this.user.isLogin = true // 登录成功后设置状态为【已登录】
          this.user.username = response.data.username // 设置当前登录用户的用户名
          this.user.avatar = response.data.avatar // 设置当前登录用户的头像链接
          // 登录成功之后查询该用户点赞过的所有留言
          await this.fetchUserLikes()
          return true // 登录成功
        } else {
          return false // 登录失败
        }
      } catch (error) {
        console.log(error)
      }
    },

    async fetchUserLikes() {
      try {
        const response = await axios({
          method: 'get',
          url: 'http://localhost:3000/user/likes',
          params: {
            username: this.user.username
          }
        })
        // 将用户点赞过的留言的 id 作为一个数组赋值给 this.user.likes
        this.user.likes = response.data.map(
          (obj: { message_id: number }) => obj.message_id
        )
      } catch (error) {
        console.log(error)
      }
    },

    async changeAvatar(userInfo: { username: string; avatar: string }) {
      try {
        const response = await axios({
          method: 'post',
          url: 'http://localhost:3000/user/avatar/change',
          data: userInfo
        })
        if (response.status === 1) {
          this.user.avatar = response.data.avatar // 修改头像
          // const token = response.data.token
          // localStorage.setItem('token', token) // 登录成功后保存token
          // axios.defaults.headers.common['Authorization'] = `Bearer ${token}` // 为之后的请求都带上token
          return true
        } else {
          return false
        }
      } catch (error) {
        console.log(error)
      }
    },

    async uploadAvatar(formData: FormData) {
      try {
        const response = await axios({
          method: 'post',
          url: 'http://localhost:3000/user/avatar/upload',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        if (response.status === 1) {
          this.user.avatar = response.data.avatar // 修改头像
          // const token = response.data.token
          // localStorage.setItem('token', token) // 登录成功后保存token
          // axios.defaults.headers.common['Authorization'] = `Bearer ${token}` // 为之后的请求都带上token
          return true
        } else {
          return false
        }
      } catch (error) {
        console.log(error)
      }
    },

    async changeUsername(userInfo: {
      oldUsername: string
      newUsername: string
    }) {
      try {
        const response = await axios({
          method: 'post',
          url: 'http://localhost:3000/user/username/change',
          data: userInfo
        })
        if (response.status === 1) {
          // const token = response.data.token
          // localStorage.setItem('token', token) // 登录成功后保存token
          // axios.defaults.headers.common['Authorization'] = `Bearer ${token}` // 为之后的请求都带上token
          return true
        } else {
          return false
        }
      } catch (error) {
        console.log(error)
      }
    },

    async logout() {
      this.user.isLogin = false
      this.user.likes = []
      this.user.username = ''
      localStorage.removeItem('token')
      // axios.defaults.headers.common['Authorization'] = ''
    }
  }
})
